const app = getApp();
const util = require("../../../utils/util.js");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    courseLibraryList: [],
    courseList: [],
    recommendList: [],
    currentRepo: {
      index: 0,
      id: "",
      courseLibraryName: "",
      urlMethod: "",
    },
    isLoadMore: false,
    page: {
      currentPage: 1,
      pageSize: 10,
      total: 0,
    },
    isGetCourseList: false,
    selectRepoTimer: "",
    isCourseEmpty: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('onLoad')
    wx.hideHomeButton();
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // let code = ["learn"];
    // let arr = util.getArrEqual(code, app.globalData.roles);
    // console.log(app.globalData.roles);
    // console.log(util.getArrEqual(code, app.globalData.roles));
    // if (arr.length > 0) {
    //   wx.setStorageSync("curPage", ["learn"]);
    // } else {
    //   util.roleToPage();
    // }
    this.setData({ courseList: [] });
    this.getCourseLibraryList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  initData() {},
  //跳转到课程详情
  toCourseDetail(e) {
    console.log(e);
    let index = e.currentTarget.dataset.index;
    let id = this.data.courseList[index].id;
    console.log(
      `/pages/learn/course-detail/courseDetail?id=${id}&courseLibraryId=${this.data.currentRepo.id}&sensors_ext=01-02&from=learning`
    );
    wx.navigateTo({
      url: `/pages/learn/course-detail/courseDetail?id=${id}&courseLibraryId=${this.data.currentRepo.id}&sensors_ext=01-02&from=learning`,
    });
  },
  //滚动到底部触发
  scrolltolower() {
    // return;
    console.log("scrolltolower");
    // if (this.data.currentRepo.index === 0) return;
    this.loadMore();
  },
  loadMore: function () {
    const { currentPage, total } = this.data.page;
    console.log(total,this.data.courseList.length,this.data.isGetCourseList);
    if (
      total > this.data.courseList.length &&
      this.data.isGetCourseList === false
    ) {
      this.setData({
        "page.currentPage": currentPage + 1,
        isLoadMore: true,
      });
      this.getRepoClassList();
    }
  },
  selectRepo(e) {
    console.log('111111');
    clearTimeout(this.data.selectRepoTimer);
    this.data.selectRepoTimer = setTimeout(() => {
      //防抖
      let index = e.currentTarget ? e.currentTarget.dataset.index : e;
      let repo = this.data.courseLibraryList[index];
      this.data.currentRepo = {
        index: index,
        id: repo.id,
        courseLibraryName: repo.courseLibraryName,
      };

      this.data.page.currentPage = 1;
      this.data.page.total = 0;
      this.setData({
        currentRepo: this.data.currentRepo,
        courseList: [],
      });

      // if (index === 0) {
      //   this.getRecommendCourse();
      // } else {
      //   this.getRepoClassList();
      // }
      this.getRepoClassList();
    }, 200);
  },
  async getCourseLibraryList() {
    let recommendList = await app.api.post({
      url: "study_course_slecetRecommendCourse",
      data: {currentPage:1, pageSize:10},
    });
    app.api
      .post({
        url: "vx_study_courseLibrary_list",
      })
      .then((res) => {
        console.log(res);
        let list = res ? res : [];
        if (recommendList.list.length>0) {
          list.unshift({
            id: '',
            courseLibraryName: '推荐课程'
          })
        }
        this.setData({
          courseLibraryList: list,
          // courseList: list[0] ? list[0].courseVxResps : [],
          currentRepo: {
            index: 0,
            id: "",
            courseLibraryName: "",
            urlMethod: "",
          },
        });
        if(list[0]){
          if (list[0].id) {
          app.api.post({
            url: "vx_study_course_list",
            data: { id: list[0].id },
          }).then(res=>{
            this.setData({
              courseList: res.list || [],
              "page.total": Number(res.total)
            })
          })
        } else {
          this.setData({
            courseList: recommendList.list || [],
            "page.total": Number(recommendList.total)
          })
        }
        }
         
        console.log(this.data);
      });
  },
  getRecommendCourse() {
    app.api
      .post({
        url: "vx_study_course_recommend",
      })
      .then((res) => {
        let isEmpty = false;
        let arr = res ? res : [];
        if (arr.length <= 0) {
          isEmpty = true;
        }
        this.setData({
          isCourseEmpty: isEmpty,
          courseList: arr,
        });
      });
  },
  async getRepoClassList() {
    console.log("this.data.isGetCourseList", this.data.isGetCourseList);
    if (this.data.isGetCourseList) return;

    let { currentRepo, page, courseList } = this.data;
    const { currentPage, pageSize } = page;
    let url = currentRepo.id?"vx_study_course_list":"study_course_slecetRecommendCourse",
    param = currentRepo.id? { id: currentRepo.id, currentPage, pageSize }: { currentPage, pageSize }
    try {
      this.data.isGetCourseList = true;
      let res = await app.api.post({
        url: url,
        data: param,
      });
      let isEmpty = false;
      let arr = this.data.courseList.concat(res.list);
      //list = this.data.courseList
      // if (this.data.isLoadMore) {
      //   console.log("执行加载");
      //   list.push(...arr);
      // } else {
      //   console.log("执行加载2");
      //   list = arr;
      // }
      if (arr.length <= 0) {
        isEmpty = true;
      }
      this.setData({
        courseList: arr,
        "page.total": Number(res.total),
        isLoadMore: false,
        isCourseEmpty: isEmpty,
      }); 
      console.log(courseList,'courseList');

      this.data.isGetCourseList = false;
    } catch (e) {
      this.data.isGetCourseList = false;
    }
  },
  goToCourse(e) {
    const { id } = e.currentTarget.dataset;
    let courseLibraryName = "";
    this.data.courseLibraryList.map((v, k) => {
      console.log(typeof v.id, typeof id);
      if (v.id === id) {
        courseLibraryName = v.courseLibraryName;
      }
    });
    console.log(courseLibraryName);
    wx.navigateTo({
      url: `/pages/learn/course/course?id=${id}&courseLibraryName=${courseLibraryName}&sensors_ext=01-02&from=`,
    });
  },
  goToCourseDetail(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/learn/course-detail/courseDetail?id=${id}`,
    });
  },
});
